package com.xb.loan.util;

import org.apache.commons.lang3.RandomStringUtils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.UUID;
import java.util.Vector;
import java.util.regex.Pattern;


/**
 * 
 * 字符串工具类
 */
public class StringUtils {
    private StringUtils() {
    }

    private static final Pattern INT_PATTERN = Pattern.compile("^\\d+$");

    public static boolean isEmpty(String s) {
        return s == null || s.trim().equals("");
    }

    public static boolean isNotEmpty(String s) {
        return !isEmpty(s);
    }
    
    public static String trimString(String str){
    	if(isNotEmpty(str)){
    		return str.trim();
    	}
    	return null;
    }
    
    /**
     * <p>Checks if a String is whitespace, empty ("") or null.</p>
     *
     * <pre>
     * StringUtils.isBlank(null)      = true
     * StringUtils.isBlank("")        = true
     * StringUtils.isBlank(" ")       = true
     * StringUtils.isBlank("bob")     = false
     * StringUtils.isBlank("  bob  ") = false
     * </pre>
     *
     * @param str  the String to check, may be null
     * @return <code>true</code> if the String is null, empty or whitespace
     */
    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

    /**
     * <p>Checks if a String is not empty (""), not null and not whitespace only.</p>
     *
     * <pre>
     * StringUtils.isNotBlank(null)      = false
     * StringUtils.isNotBlank("")        = false
     * StringUtils.isNotBlank(" ")       = false
     * StringUtils.isNotBlank("bob")     = true
     * StringUtils.isNotBlank("  bob  ") = true
     * </pre>
     *
     * @param str  the String to check, may be null
     * @return <code>true</code> if the String is
     *  not empty and not null and not whitespace
     */
    public static boolean isNotBlank(String str) {
        return !StringUtils.isBlank(str);
    }

    public static String generateUUID() {
        return StringUtils.replace(UUID.randomUUID().toString(), "-", "").toUpperCase();
    }

    public static String replace(String text, String repl, String with) {
        return replace(text, repl, with, -1);
    }

    public static String replace(String text, String repl, String with, int max) {
        if (isEmpty(text) || isEmpty(repl) || with == null || max == 0) {
            return text;
        }
        int start = 0;
        int end = text.indexOf(repl, start);
        if (end == -1) {
            return text;
        }
        int replLength = repl.length();
        int increase = with.length() - replLength;
        increase = (increase < 0 ? 0 : increase);
        increase *= (max < 0 ? 16 : (max > 64 ? 64 : max));
        StringBuffer buf = new StringBuffer(text.length() + increase);
        while (end != -1) {
            buf.append(text.substring(start, end)).append(with);
            start = end + replLength;
            if (--max == 0) {
                break;
            }
            end = text.indexOf(repl, start);
        }
        buf.append(text.substring(start));
        return buf.toString();
    }

    public static boolean hasLength(String str) {
        return (str != null && str.length() > 0);
    }

    public static boolean hasText(String str) {
        if (!hasLength(str)) {
            return false;
        }
        int strLen = str.length();
        for (int i = 0; i < strLen; i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param e
     * @return string
     */
    public static String toString(Throwable e) {
        StringWriter w = new StringWriter();
        PrintWriter p = new PrintWriter(w);
        p.print(e.getClass().getName());
        if (e.getMessage() != null) {
            p.print(": " + e.getMessage());
        }
        p.println();
        try {
            e.printStackTrace(p);
            return w.toString();
        } finally {
            p.close();
        }
    }

    /**
     * @param msg
     * @param e
     * @return string
     */
    public static String toString(String msg, Throwable e) {
        StringWriter w = new StringWriter();
        w.write(msg + "\n");
        PrintWriter p = new PrintWriter(w);
        try {
            e.printStackTrace(p);
            return w.toString();
        } finally {
            p.close();
        }
    }

    public static String concat(String... strings) {
        if (strings == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (String str : strings) {
            if (str != null) {
                sb.append(str);
            }
        }
        return sb.toString();
    }

    public static boolean isInteger(String str) {
        if (str == null || str.length() == 0) return false;
        return INT_PATTERN.matcher(str).matches();
    }

    public static String[] paser(String inStr, String sep) {
        String[] resStrArr = null;

        if (inStr == null) {
            return resStrArr;
        }

        int endIndex = 0;
        String tmpStr = inStr;

        if (tmpStr.startsWith(sep)) {
            tmpStr = tmpStr.substring(sep.length());
        }

        Vector resVect = new Vector();

        while (true) {
            endIndex = tmpStr.indexOf(sep);

            if (endIndex == -1) {
                resVect.addElement(tmpStr);
                break;
            }

            resVect.addElement(tmpStr.substring(0, endIndex));

            if (tmpStr.length() > (endIndex + 1)) {
                tmpStr = tmpStr.substring(endIndex + 1);
            } else {
                break;
            }
        }

        resStrArr = new String[resVect.size()];

        for (int i = 0; i < resVect.size(); i++) {
            resStrArr[i] = (String) resVect.get(i);
        }

        return resStrArr;
    }

    public static String ignoreNull(String srcStr) {
        if (srcStr == null) {
            return "";
        } else {
            return srcStr;
        }
    }

    /**
     * insert special char to current string. for example source:"abcdef";special string:'s'
     * , if special len for 10, result str:"ssssabcdef".
     * @param maxLen int
     * @param source String
     * @param fillChar char
     * @return String
     */
    public static String insertCharToLen(int maxLen, String source, char fillChar) {
        if (source == null) {
            source = "";
        }

        String resStr = source;
        int len = resStr.length();
        StringBuffer sb = new StringBuffer(resStr);

        for (int i = 0; i < (maxLen - len); i++) {
            sb.insert(0, fillChar);
        }

        return sb.toString();
    }

    /**
    * fill special char to current string, for example source:"abcdef";special string:'s'
    * , if special len for 10, result str:"abcdefssss".
    * @param maxLen int
    * @param source String
    * @param fillChar String
    * @return String
    */
    public static String appendCharToLen(int maxLen, String source, char fillChar) {
        if (source == null) {
            source = "";
        }

        String resStr = source;
        int len = resStr.length();
        StringBuffer sb = new StringBuffer(resStr);

        for (int i = 0; i < (maxLen - len); i++) {
            sb.append(fillChar);
        }

        return sb.toString();
    }

    /*ȥ����ߴ�0���ַ�*/
    public final static String trimZero(String inStr) {
        String str = "0";

        if (inStr == null || "".equals(inStr)) {
            return str;
        }

        byte[] b = inStr.trim().getBytes();

        for (int i = 0; i < b.length; i++) {
            if (b[i] != '0') {
                str = new String(b, i, b.length - i);
                break;
            }

            if (i == b.length - 1) {
                return "0";
            }
        }

        return str;
    }

    /**
    * 对 有 分割符 的字符 排序，对 出球 号码 进行排序
    * @param bassString 原始串，
    * @param splitstr   分割符合
    * @return
    */
    public static String StringSort(String bassString, String splitstr) {
        String[] bassArray = bassString.split(splitstr);
        Arrays.sort(bassArray);
        String resuit = "";
        for (int i = 0; i < bassArray.length; i++) {
            resuit += bassArray[i] + splitstr;
        }
        resuit = resuit.substring(0, resuit.length() - 1);
        return resuit;
    }

    public static boolean isNull(String str) {
        if (str == null || "".equalsIgnoreCase(str)) return true;

        return false;
    }
    
    public static boolean isNull(String ...strings){
        
        for(String str : strings){
            
            if(isNull(str)){
                return true;
            }
        }
        return false;
    }
    
    /**
    * 在串中查找指定字符出现次数
    * 
    * @param
    * @return 出现次数
    */
    public static int characterTimes(String msg, String cha) {
        int times = 0;
        int fromIndex = 0;

        while (fromIndex != -1) {
            fromIndex = fromIndex + 1;
            fromIndex = msg.indexOf(cha, fromIndex);
            if (fromIndex != -1) {
                times = times + 1;
            }
        }

        return times;
    }

   /* *//**
    * 从后开始替换字符串函数
    * 
    * @param String strSource - 源字符串 
    * @param String strFrom要替换的子串
    *  @param String strTo替换为的字符串
    * @return boolean
    *//*
    public static String replace(String strSource, String strFrom, String strTo) {
        if (strFrom == null || strFrom.equals("")) return strSource;

        String strDest = "";
        int intPos;
        int intSourceLen = strSource.length();

        if ((intPos = strSource.lastIndexOf(strFrom)) != -1) {
            strDest = strDest + strSource.substring(0, intPos);
            strDest = strDest + strTo;

            intPos = intPos + 1;
            strSource = strSource.substring(intPos, intSourceLen);
        }

        strDest = strDest + strSource;

        return strDest;
    }
*/
    /**
    * 替换所有指定字符串函数
    * 
    * @param  strSource String- 源字符串
    * @param  strFrom String要替换的子串
    * @param  strTo String替换为的字符串
    * @return boolean
    */
    public static String replaceAll(String strSource, String strFrom, String strTo) {
        if (strFrom == null || strFrom.equals("")) return strSource;

        String strDest = "";
        int statrPos = 0;
        int endPos;
        @SuppressWarnings("unused")
        int strToLen = strTo.length();

        while ((endPos = strSource.indexOf(strFrom, statrPos)) != -1) {
            strDest = strDest + strSource.substring(statrPos, endPos);
            strDest = strDest + strTo;
            statrPos = endPos + 1;
            System.out.println("strDest::" + strDest);
        }

        if (statrPos != 0) {
            strDest = strDest + strSource.substring(statrPos, strSource.length());
            return strDest;
        }

        return strSource;
    }

    /**
    * 取指定长度字符串
    * 
    * @param strSource
    * @param intPos
    * @return
    */
    public static String subString(String strSource, int intPos) {
        String sub = "0";
        int intSourceLen = strSource.length();
        if (intSourceLen > intPos) {
            sub = strSource.substring(intPos, intSourceLen);
        }
        return sub;
    }

    public static String replaceNewLine(String in) {
        if (in == null) return null;

        char ch;
        char[] input = in.toCharArray();
        int len = input.length;
        final StringBuffer out = new StringBuffer((int) (len * 1.3));
        for (int index = 0; index < len; index++) {
            ch = input[index];
            if (ch == '\n')
                out.append("<br>");
            else if (ch == ' ')
                out.append("&nbsp;");
            else if (ch == '<')
                out.append("&lt;");
            else if (ch == '>')
                out.append("&gt");
            else
                out.append(ch);
        }
        return out.toString();
    }

    public static String transferGb2312(String in) {
        String out = null;
        try {
            byte[] ins = in.getBytes("iso-8859-1");
            out = new String(ins, "gb2312");
        } catch (Exception e) {
        }
        return out;
    }

    public static String transferISO8859(String in) {
        String out = null;
        try {
            byte[] ins = in.getBytes("gb2312");
            out = new String(ins, "iso-8859-1");
        } catch (Exception e) {
        }
        return out;
    }

    /**
    * 返回指定长度的字符串，如果原字符串长度超过指定长度，
    * 则只返回原字符串的前 面的字符，并且在后面加“...”
    * 
    * @param str 源字符串 
    * @param length 要返回的指定长度
    * @return 返回指定长度的字符串
    */
    public static String getShortString(String str, int length) {
        String result;

        if (str.length() > length) {
            result = str.substring(0, length) + "...";
        } else {
            result = str;
        }
        return result;
    }

    public static String convertIso8859ToGb2312(String in) {
        String out = null;
        try {
            byte[] ins = in.getBytes("iso-8859-1");
            out = new String(ins, "gb2312");
        } catch (Exception e) {
        }
        return out;
    }

    public static String convertGb2312ToIso8859(String in) {
        String out = null;
        try {
            byte[] ins = in.getBytes("gb2312");
            out = new String(ins, "iso-8859-1");
        } catch (Exception e) {
        }
        return out;
    }

    //   public static String createRandomString() {
    //       //产生随机字符串
    //       String random = RandomStringUtils.randomAlphabetic(10);
    //       //随机字符串再加上当前的日期时间 long
    //       random += DateUtils2.getNowTimestamp().getTime();
    //       return random;
    //   }

    public static String createRandomPassword() {
        String random = null;
        //产生随机字符串
        random = RandomStringUtils.randomAlphabetic(6);
        return random;
    }

    /**
    * 处理文件名
    * 包括：
    * 1、文件名中的空格替换为下划线
    * 2、暂时没有了
    */
    public static String transactFilename(String filename) {
        String rtn = StringUtils.replace(filename, " ", "_");
        return rtn;
    }

    public static String[] split(String str, char delim) {

        if (str == null) return null;
        if (str.trim().equals("")) return new String[0];

        int count = 1;
        char c[] = str.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == delim) {
                count++;
            }
        }

        String s[] = new String[count];
        int index = 0;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == delim) {
                s[index] = sb.toString();
                sb = new StringBuffer();
                index++;
            } else {
                sb.append(c[i]);
            }
        }
        s[index] = sb.toString();
        return s;
    }

    /**
    * url编码，将url中的汉字和特殊字符转换成浏览器能够识别的GBK编码
    */
    public static String urlEncoder(String s) {

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '/') || (c == '.') || (c == '\\') || (c == ':')) {//c >= 0 && c <= 255 && c != '%'
                sb.append(c);
            } else {
                byte[] b;
                try {
                    b = Character.toString(c).getBytes("GB2312");
                } catch (Exception ex) {
                    ex.printStackTrace(System.err);
                    b = new byte[0];
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0) k += 256;
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }

    /**
    * 给字符串添加换行符号，本方法使用于网页
    * @param s
    * @return
    */
    public static String addNewLine(String s, int len) {
        StringBuffer sb = new StringBuffer();
        if (s != null) {
            int slen = s.length();
            for (int i = 0; i < slen; i += len) {
                String temp = "";
                if (i + len < slen) {
                    temp = s.substring(i, i + len);
                } else {
                    temp = s.substring(i, slen);
                }
                if (i != 0) {
                    sb.append("<br>");
                }
                sb.append(temp);
            }
        }
        return sb.toString();
    }

}
